package com.zjs.jsp.ediorder.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjs.jsp.domain.axd.AxdOrderRootData;
import com.zjs.jsp.domain.axd.out.AxdOutData;
import com.zjs.jsp.domain.config.WebHelpService;
import com.zjs.jsp.ediorder.domain.mongodb.jsp_Status;
import com.zjs.jsp.ediorder.service.mongodb.Jsp_StatusRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author 李文
 * @create 2017-10-13 13:48
 **/
public abstract class BaseOrderQueryService
{
    private static final Logger LOGGER_FACTORY = LoggerFactory.getLogger(BaseOrderQueryService.class);

    private static final ObjectMapper JSON = new ObjectMapper();

    @Autowired
    private Jsp_StatusRepository o;



    public String queryOrder(Object rootData, String uuid) {
        AxdOrderRootData root = (AxdOrderRootData) rootData;
        try {
            boolean b = root.getPartner_order_code().size() > 10;
            if (b) {
                LOGGER_FACTORY.error(uuid + "  订单号数量大于1 ：", new Exception("订单号数量大于1 "));
                return WebHelpService.getString(40000, "订单号数量大于1");
            }
        } catch (Exception e) {
            LOGGER_FACTORY.error(uuid + "  获取请求订单号错误 ：" + e.getMessage(), e);
            return WebHelpService.getString(40000, "获取请求订单号错误");
        }
        try {
            List<jsp_Status> orderStatusList = o.findByPartner_order_code(root.getPartner_order_code());
            Map<String, List<jsp_Status>> map = new HashMap<>();
            for (jsp_Status status : orderStatusList) {
                List<jsp_Status> s = map.get(status.getPoc());
                if (s == null) {
                    s = new ArrayList<>();
                    s.add(status);
                    map.put(status.getPoc(), s);
                } else {
                    s.add(status);
                }
            }

            AxdOutData axd = new AxdOutData();
            axd.setCode(200);
            axd.setMsg("成功");
            List<Object> data = new ArrayList<>();
            for (List<jsp_Status> s : map.values()) {
                Collections.sort(s);
                getDate(data, s);
            }
            axd.setData(data);
            String sou = JSON.writeValueAsString(axd);
            LOGGER_FACTORY.info(uuid + " 响应的数据是 " + sou);
            return sou;
        } catch (Exception e) {
            LOGGER_FACTORY.error(uuid + "查询出错 " + e.getMessage(), e);
            return WebHelpService.getString(40000, "查询出错");
        }
    }


    public abstract void getDate(List<Object> data, List<jsp_Status> s) throws Exception;
}
